package com.gage.controller.admin;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.gage.controller.base.BaseController;
import com.gage.commons.result.BaseConditionVO;
import com.gage.model.shiro.ShiroUser;
import com.gage.commons.utils.Common;
import com.gage.commons.utils.DateUtils;
import com.gage.commons.utils.FileUtils;
import com.gage.commons.utils.ImageTools;
import com.gage.commons.utils.JsonDateValueUtil;
import com.gage.commons.utils.StringUtils;
import com.gage.model.SysAccessory;
import com.gage.model.SysAlbum;
import com.gage.service.ISysAblumService;

@Controller
@RequestMapping({"/admin/album"})
public class SysAlbumController extends BaseController{
	@Autowired
	private ISysAblumService sysAblumService;
	
	@RequestMapping("/index")
	public String index(HttpServletRequest request){
		return "/admin/album/index";
	}
	@RequestMapping("/openupload")
	public String openUpload(HttpServletRequest request){
		return "/admin/album/upload";
	}
	/**
	 * 加载树
	 * @author lkr
	 * @date:20170512
	 * @param request
	 * @param id
	 * @return
	 */
	@PostMapping("/tree")
    @ResponseBody
	public Object getAlbumTree(HttpServletRequest request)
	{
		Integer userid=Integer.parseInt(this.getShiroUser().getId().toString());
		return sysAblumService.selectAlbumTree(userid);
	}
	
	 /**
     * 添加相册页
      * @author lkr
      * @date:20170512
     * @return
     */
    @GetMapping("/add")
    public String addPage(Model model) {
        return "admin/album/edit";
    }
    /**
     * 编辑相册页
     *
     * @return
     */
    @GetMapping("/edit")
    public String editPage(String id,Model model) {
    	SysAlbum album=null;
    	if (StringUtils.isNotEmpty(id)) {
    		int aid=Integer.parseInt(id);
    		album=	sysAblumService.selectByPrimaryKey(aid);
		}
    	model.addAttribute("album", album);
        return "admin/album/edit";
    }
    /**
     * @author lkr
     * @date:20170512
     * @param album
     * @param result
     * @return
     */
    @PostMapping("/save")
    @ResponseBody
	public Object save(@Valid SysAlbum album, BindingResult result)
	{
    	int status=0;
		ShiroUser u = this.getShiroUser();
		int userId=Integer.parseInt(u.getId().toString());
		album.setUserId(userId);
		if (StringUtils.isEmpty(album.getId())) {
			album.setCreateDate(new Date());
			status=sysAblumService.insertSelective(album);
		}else {
			status=sysAblumService.updateByPrimaryKeySelective(album);
		}
		if (status<=0) {
			return resultJson("0","网络故障","");
		}
		return resultJson("1","信息保存成功","");
	}
    /**
     * 删除栏目
     * @author lkr
 	 * @date:20170512
     * @param id
     * @return
     */
    @PostMapping("/delete")
    @ResponseBody
    public Object delete(String id) {
    	int count=0;
    	if (StringUtils.isNotEmpty(id)) {
    		count=sysAblumService.deleteByPrimaryKey(Integer.parseInt(id));
    		return resultJson("1","操作成功","");
		}else {
			return resultJson("1","网络故障","");
		}
    }
   
    @PostMapping("/ImageList")
    @ResponseBody
	public Object SelectImageList(HttpServletRequest request,BaseConditionVO vo,String albumId){
		String jsonString="";
		Integer totalCount=sysAblumService.selectImageListCount(albumId,this.getUserId().toString());
		vo.setTotalCount(totalCount);
		List<SysAccessory> list=sysAblumService.selectImageList(vo,albumId,this.getUserId().toString());
		List<SysAccessory> reList=new ArrayList<SysAccessory>();
		for (SysAccessory sysAccessory : list) {
			sysAccessory.setUrl(sysAccessory.getPath()+"/"+sysAccessory.getName());
			reList.add(sysAccessory);
		}
		JsonConfig jsonConfig = new JsonConfig(); // 解决时间格式
		jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueUtil());
		jsonConfig.setIgnoreDefaultExcludes(false);
		JSONArray array = JSONArray.fromObject(reList,jsonConfig);		
			jsonString="{\"total\":"+totalCount+",\"rows\":"+array.toString()+"}";
			return jsonString;
	}
    /**
     * @author lkr
     * @date:20170512
     * @param album
     * @param result
     * @return
     */
    @PostMapping("/saveImage")
    @ResponseBody
	public Object editImage(@Valid SysAccessory accessory, BindingResult result)
	{
    	int status=0;
    	int id=0;
    	if (StringUtils.isNotEmpty(accessory.getId())) {
    		id=Integer.parseInt(accessory.getId().toString());
		}
    	SysAccessory sysAccessory =sysAblumService.selectAccessoryByPrimaryKey(id);
    	sysAccessory.setDescription(accessory.getDescription());
    	sysAccessory.setLikename(accessory.getLikename());
    	status=sysAblumService.updateSysAccessoryById(sysAccessory);
		if (status<=0) {
			return resultJson("0","网络故障","");
		}
		return resultJson("1","信息保存成功","");
	}
    /**
     * 删除
     * @author lkr
 	 * @date:20170512
     * @param id
     * @return
     */
    @PostMapping("/deleteImage")
    @ResponseBody
    public Object deleteImage(String id) {
    	String[] ids = id.split(",");
    	List<String> list = new ArrayList<String>();
		for (int i = 0; i < ids.length; i++){
			list.add(ids[i].trim());
		}
		if (this.sysAblumService.deleteByIds(list)>0)
		{
			return renderSuccess("成功删除"+ids.length+"条信息！");
		} else
		{
			return renderError("删除失败，删除操作出错！");
		}
    }
    @RequestMapping("/openImageWin")
	public String openImageWin(HttpServletRequest request){
		return "/admin/common/win-album";
	}
}
